package com.sxyc.weixin.controller;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.sxyc.tintin.controller.CommonController;
import com.sxyc.tintin.model.Device;
import com.sxyc.tintin.model.DeviceBinding;
import com.sxyc.utils.WeixinUtil;
import com.sxyc.weixin.m2m.TerminalDetailsService;

public class WeixinUnBindController extends Controller{
	/**
     * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
     * ApiConfig 属性值
     */
    public ApiConfig getApiConfig() {
        return WeixinUtil.getApiConfig();
    }
    
    /**
     * 系统设置
     */
	public void index(){
		String code = getPara("code");
		String openId = (String) getRequest().getSession().getAttribute("openId");
		if(openId == null && code == null){
			String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(),PropKit.get("domain")+"/UnBind", true);
			redirect(url);
		}else{
			if(openId == null){
				SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(), getApiConfig().getAppSecret(),code);
				openId = accessToken.getOpenid();
				getRequest().getSession().setAttribute("openId", openId);
			}
			DeviceBinding user = DeviceBinding.dao.getWxUserByOpenId(openId);
			if(user==null){
				renderJsp("bind.jsp");
			}else{
				Device device=Device.dao.getDevice(user.get("DeviceId"));
				System.out.println("device : " + device);
				this.setAttr("device",device);
				this.setAttr("openId",openId);
				renderJsp("unbind.jsp");
			}
		}
	}
	
	
	/**
	 * 设备解绑
	 */
	public void unBind(){
		String message="";
		String OpenId=this.getPara("OpenId");
		message = CommonController.unBinding(OpenId);
		System.out.println("message--->"+message);	
		if(message!=null && !"".equals(message)){
			JSONObject jo = new JSONObject();
			jo.put("message", message);
			renderJson(jo);
		}
	}
}
